# —*— coding: utf-8 -*-

import os
import numpy as np
import pandas as pd

from docx.document import Document

from docx.text.paragraph import Paragraph
from docx.text.run import Run

from docx.table import Table

from docx.shared import Inches, Pt, RGBColor

from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

from docx.oxml import parse_xml
from docx.oxml.ns import qn, nsdecls

from openpyxl import load_workbook
from openpyxl.workbook.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet
from openpyxl.cell.cell import Cell

from py_word import Word, py_dir_path, picture_path


def write_table(table: Table):
    """写入表格"""

    n = 4
    df = pd.DataFrame(data=np.arange(0, n * n, 1).reshape(n, n))
    print(df.head())

    for i in range(df.index.size):
        table.add_row()
        for j in range(df.iloc[i].index.size):
            cell_add_text(table.cell(i + 1, j), str(df.loc[i, j]),
                          english_font='Times New Roman', chinese_font='宋体', font_size=12)
            pass
        pass

    # 合并单元格
    table.cell(1, 4).merge(table.cell(df.index.size, 4))
    table.cell(1, 4).text = 'table.cell.merge.text'

    pass


def cell_add_text(cell, text, english_font='Times New Roman', chinese_font='宋体', font_size=12, font_bold=False,
                  font_color=RGBColor(0, 0, 0),
                  vertical_alignment=WD_CELL_VERTICAL_ALIGNMENT.CENTER,
                  alignment=WD_PARAGRAPH_ALIGNMENT.CENTER):
    cell.vertical_alignment = vertical_alignment
    paragraph: Paragraph = cell.paragraphs[0]
    paragraph.alignment = alignment
    run: Run = paragraph.add_run(text)
    # 西文字体
    run.font.name = english_font
    # 中文字体
    chinese_font = english_font if chinese_font is None else chinese_font
    run._element.rPr.rFonts.set(qn('w:eastAsia'), chinese_font)
    # 字体设置
    run.font.size = Pt(font_size)
    run.font.bold = font_bold
    run.font.color.rgb = font_color
    pass


def cell_fill_color(cell, color):
    fill_color_xml = parse_xml(r'<w:shd {} w:fill="{}"/>'.format(nsdecls('w'), color))
    cell._tc.get_or_add_tcPr().append(fill_color_xml)
    pass


def merge_table(document: Document):
    excel_path = os.path.join(py_dir_path, 'table.xlsx')
    workbook: Workbook = load_workbook(excel_path)
    worksheet: Worksheet = workbook['Sheet1']

    table = document.add_table(worksheet.max_row, worksheet.max_column, style='Table Grid')
    for i in range(worksheet.max_row):
        for j in range(worksheet.max_column):
            cell: Cell = worksheet.cell(i + 1, j + 1)
            table.cell(i, j).text = str(cell.value)
            pass
        pass
    pass


if __name__ == '__main__':
    document_path = os.path.join(py_dir_path, 'table.docx')
    document: Document = Word(document_path)
    print('-' * 49, end='')
    for table in document.tables:
        for i, row in enumerate(table.rows):
            print(end='\n| ')
            for j, cell in enumerate(row.cells):
                print(table.cell(i, j).text, end='\t | ')
                pass
            pass
        print('\n' + '-' * 49, end='')
        pass

    # 表格样式：网格型
    # table = document.add_table(1, 5, style='Table Grid')
    # write_table(table)

    merge_table(document)

    # 另存为
    document.save(os.path.join(py_dir_path, 'word.docx'))
    pass
